<?php

declare(strict_types=1);

namespace App\Common\Libary\Third;

use Itaoke\ItkTopClient;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use function Hyperf\Collection\data_get;

class Fanli
{

    private string $supserKl;

    public string $activityId = '20150318020002508';

    public function _get_itk_top()
    {
        vendor('Itaoke.ItkTopClient');
        $top = new ItkTopClient();
        $top->appkey = '1037161345';
        $top->secretKey = '1fa6ae26-fee4-3265-b7ce-2167d2754be9';
        return $top;
    }

    /**
     * 获取超级链接
     * @param string $pid
     * @param mixed $rId
     * @param mixed $activtyId
     * @param string $session
     * @param string $title
     * @param int $num
     * @return string
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function tranfromActivity(string $pid , mixed $rId, mixed $activtyId ,string $session, string $title = '双11红包主场,最高可领1111元',int $num=1): string
    {
        if($this->supserKl){
            return $this->supserKl;
        }
        !$activtyId && $activtyId = $this->activityId;
        $tb_top = $this->_get_itk_top();
        $req = $tb_top->load_api('ItaokeActivityTranfromGetRequest');
        $req->setPid($pid);
        $req->setUnionId("");
        $req->setPromotionSceneId($activtyId);
        $req->setRelationId($rId);
        $req->putOtherTextParam("sessionKey" ,$session );
        $resp = (array)$tb_top->execute($req );
        unset($req);
        unset($tb_top);

        if($num>2){
            logger()->info('活动失败'.$pid."--".$activtyId,$resp);
            return '';
        }
        $shortUrl = data_get($resp,'data.short_url');
        $url = data_get($resp,'data.url');
        if(!$shortUrl && !$url){
            $num++;
            //重试
            return $this->tranfromActivity($pid, $rId, $activtyId, $session,$title,$num);
        }
        $url = $shortUrl ? $shortUrl : $url;
        $taokoen = $this->_getTpwd($title, $url);
        //替换标志
        $newString = getBeString("¥", "¥", $taokoen);
        $this->supserKl = "( CZ0001 ".$newString.")";
        return $this->supserKl;
    }

    /**
     * 计算淘口令
     * @param string $title
     * @param string $url
     * @param string $pic_url
     * @param int $num
     * @return array|false|mixed
     */
    private function _getTpwd(string $title, string $url,string $pic_url = '',int $num=1)
    {
        $url = urlencode($url);
        $tb_top = $this->_get_itk_top();
        $req = $tb_top->load_api('ItaokeTpwdAppCreateRequest');
        $req->setText($title ? $title : '很不错的商品推荐给大家');
        $req->setUrl($url);
        $req->setLogo($pic_url);
        $resp = $tb_top->execute($req);
        if(!$resp) $resp = objtoarr($resp);

        if($num > 3){
            return false;
        }
        $taoken = data_get($resp,'data.password_simple');
        if(!$taoken){
            $num++;
            return $this->_getTpwd($title, $url,$pic_url ,$num);
        }
        unset($req);
        unset($tb_top);
        return $taoken;
    }

    /**
     * 京东转链接
     * @param $content
     * @param $urls
     * @return array|mixed|string|string[]
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function tranSearchJd($content ,$urls, $pid = ''): mixed
    {
        $jd = new Jd();
        foreach ($urls as $v){
            if(strpos($v,'jd.com')===false && strpos($v, '#小程序://京喜') === false){
                continue;
            }
            $jd = $jd->setPid($pid)->setExternalInfo();
            //京喜
            if(str_contains($v, '#小程序://京喜')){
                $res = $jd->transformJx($v);
                $clickUrl = $res['data']['wxTextChain'];
                !$clickUrl && logger()->debug($content."京喜团转链接失败，地址：{$v}",$res);
            }else{
                //判断是否是已转化之后的地址，是的话则直接转链接保持原来的内容
                if(str_contains($v, "u.jd.com")){
                    $res = $jd->transform($v);
                }else{
                    //搜索内容
                    $sarch = $jd->search($v);
                    $link = '';
                    if(!empty($sarch)){
                        $datail = $sarch[0];
                        $quanInfo = $jd->getMaxCoupon($datail['couponInfo']['couponList'] ,$datail['priceInfo']['price'] );
                        $quanInfo['link'] && $link = $quanInfo['link'];
                    }
                    $res = $jd->transform($v, $link);
                }
                $clickUrl = $res['shortURL'] ?? '';
            }
            if($clickUrl){
                $content = str_replace($v,$clickUrl,$content);
            }
            unset($quanInfo);
        }
        return $content;
    }

    /**
     * 惊喜商品转链接
     * @param $content
     * @param $urls
     * @param $robotInfo
     * @param $groupInfo
     * @param $robotSet
     * @return array|mixed|string|string[]
     */
    public function tranSearchJx($content ,$urls,$robotInfo=[] ,$groupInfo=[],$robotSet = []){
        $jd = new Jd();
        foreach ($urls as $v){
            //调用最新机制转链接
            $res = $jd->setExternalInfo('')->transformJx($v);
            $clickUrl = $res['data']['wxTextChain'];
            if($clickUrl || $robotSet['rbt_tran_fail']['cv_value']){
                $content = str_replace($v,$clickUrl,$content);
            }
        }
        unset($tb_top);
        return $content;
    }
}